const express = require("express");
const { Course, Category, User, Chapter } = require("../../models");
const router = express.Router();
const Sequelize = require("sequelize");
const { NotFoundError } = require("../../utils/errors");
const { success, failure } = require("../../utils/responses");
const Op = Sequelize.Op;

/**
 * 获取课程列表
 * GET /admin/courses
 */
router.get("/", async function (req, res) {
  try {
    const query = req.query;
    const currentPage = Math.abs(Number(query.currentPage)) || 1;
    const pageSize = Math.abs(Number(query.pageSize)) || 10;
    const offset = (currentPage - 1) * pageSize;
    const condition = {
      ...getCondition(),
      order: [["id", "DESC"]],
      offset,
      limit: pageSize,
    };
    if (query.categoryId) {
      condition.where = {
        categoryId: {
          [Op.eq]: query.categoryId,
        },
      };
    }

    if (query.userId) {
      condition.where = {
        userId: {
          [Op.eq]: query.userId,
        },
      };
    }

    if (query.name) {
      condition.where = {
        name: {
          [Op.like]: `%${query.name}%`,
        },
      };
    }

    if (query.recommended) {
      condition.where = {
        recommended: {
          // 需要转布尔值
          [Op.eq]: query.recommended === "true",
        },
      };
    }

    if (query.introductory) {
      condition.where = {
        introductory: {
          [Op.eq]: query.introductory === "true",
        },
      };
    }

    const courses = await Course.findAndCountAll(condition);
    success(res, "Get courses successfully", {
      courses: courses.rows,
      total: courses.count,
      currentPage,
      pageSize,
    });
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 根据id获取课程
 * GET /admin/courses/:id
 */
router.get("/:id", async function (req, res) {
  try {
    const course = await getCourse(req);
    success(res, "Get course successfully", { course });
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 创建课程
 * POST /admin/courses
 */
router.post("/", async function (req, res) {
  try {
    const body = filterBody(req.body);
    body.userId = req.user.id;
    const course = await Course.create(body);
    success(res, "Create course successfully", { course }, 201);
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 删除课程
 * DELETE /admin/courses/:id
 */
router.delete("/:id", async function (req, res) {
  try {
    const course = await getCourse(req);
    const count = await Chapter.count({
      where: { courseId: req.params.id },
    });
    if (count > 0) {
      throw new Error("该课程下存在章节，请先删除章节后再删除课程");
    }
    await course.destroy();
    success(res, "Delete course successfully");
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 更新课程
 * PUT /admin/courses/:id
 */
router.put("/:id", async function (req, res) {
  try {
    const course = await getCourse(req);
    await course.update(filterBody(req.body));
    success(res, "Update course successfully", { course });
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 公共方法： 过滤请求体
 */
function filterBody(body) {
  const { categoryId, name, image, recommended, introductory, content } = body;
  return {
    categoryId,
    name,
    image,
    recommended,
    introductory,
    content,
  };
}

/**
 * 公共方法： 获取关联查询条件
 */
function getCondition() {
  return {
    attributes: {
      exclude: ["categoryId", "userId"],
    },
    include: [
      {
        model: Category,
        as: "category",
        attributes: ["id", "name"],
      },
      {
        model: User,
        as: "user",
        attributes: ["id", "username", "avatar"],
      },
    ],
  };
}

/**
 * 公共方法： 查询当前课程
 */
async function getCourse(req) {
  const condition = getCondition();
  const { id } = req.params;
  const course = await Course.findByPk(id, condition);
  if (!course) {
    throw new NotFoundError(`ID: ${id}的课程未找到`);
  }
  return course;
}

module.exports = router;
